package com.hctforgreen.greenservice.ctr;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;

import com.hctforgreen.greenservice.db.DbAdapter;
import com.hctforgreen.greenservice.db.DbColumnAdapter;
import com.hctforgreen.greenservice.db.DbEntryAdapter;
import com.hctforgreen.greenservice.model.BookListEntity;
import com.hctforgreen.greenservice.model.BookListEntity.BookEntity;
import com.hctforgreen.greenservice.model.ColumnListEntity;
import com.hctforgreen.greenservice.model.ColumnListEntity.ColumnEntity;
import com.hctforgreen.greenservice.model.DataVersionCodeEntity;
import com.hctforgreen.greenservice.model.MachineListEntity;
import com.hctforgreen.greenservice.model.MachineListEntity.MachineEntity;
import com.hctforgreen.greenservice.model.SerieListEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.ChildSerieEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.SerieEntity;
import com.hctforgreen.greenservice.utils.DownloadBookLstInitFinishUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LogUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;

/**
 * 更新系列，机型 ，资料
 * 
 * @author denghb
 * 
 */
public class UpdateController extends BaseController {

	public UpdateController(Context context) {
		super(context);
	}

	public UpdateController(DbEntryAdapter dbAdapter) {
		super(dbAdapter);
	}

	// ///
	/**
	 * 1、所有系列信息(不支持翻页)
	 * 
	 * @return
	 * @throws Exception
	 */
	public HctResult getAllSeries(boolean bTopRefresh) throws Exception {
		HctResult result = new HctResult();

		HctBackTestJsonController controller = new HctBackTestJsonController(
				context);

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

		SerieListEntity listEntity = null;
		if (!bTopRefresh) {
			/**
			 * 首先尝试从db中查询
			 */
			List<SerieEntity> serieEntities = selectSerieListFromDb();
			if (serieEntities.size() > 0) {
				listEntity = new SerieListEntity();
				listEntity.dataList = serieEntities;
			}
			/**
			 * 查询不到则从服务器获取
			 */
			else {
				listEntity = getAllSeriesFromNetAndInsert2Db(controller, params);
			}
		} else if (bTopRefresh) {
			listEntity = getAllSeriesFromNetAndInsert2Db(controller, params);
		}

		if (listEntity.dataList != null) {
			result.status = HctConstants.STATUS_SUCCESS;
			if (listEntity.dataList.size() > 0) {

				result.data = listEntity.dataList;
				result.totalSize = listEntity.dataList.size();
			}
		} else {
			result.status = HctConstants.STATUS_FAILD;
		}
		return result;
	}

	private SerieListEntity getAllSeriesFromNetAndInsert2Db(
			HctBackTestJsonController controller,
			ArrayList<NameValuePair> params) throws Exception, JSONException {
		SerieListEntity listEntity;
		String jsonString = !controller.isB_DEBUG() ? mServerAdapter
				.invokeServerGet(HctConstants.NET_SYNC_DATA_MOBILE_PATH,
						GET_ALL_SERIES_ACTION, params) : controller
				.getAllSeries();

		JSONObject jsonObject = new JSONObject(jsonString);

		listEntity = SerieListEntity.parse(jsonObject, context);

		if (listEntity.dataList != null) {
			insertSerieList2Db(listEntity);
		}
		return listEntity;
	}

	/**
	 * 将获取到的"所有系列信息"插入db
	 */
	private void insertSerieList2Db(SerieListEntity listEntity) {
		/**
		 * 插入db
		 */
		DbController dbController = new DbController(new DbAdapter(context));
		dbController.insert(listEntity);
	}

	/**
	 * 从db查询出"所有系列信息"
	 * 
	 * @return
	 */
	private List<SerieEntity> selectSerieListFromDb() {
		/**
		 * 插入db
		 */
//		DbController dbController = new DbController(new DbAdapter(context));
		DbController dbController = new DbController(context);
		return dbController.getSerieEntityLst();
	}

	// ////////////////
	/**
	 * 2、所有机型信息(不支持翻页)
	 * 
	 * @return
	 * @throws Exception
	 */
	public HctResult getAllMachines(boolean bTopRefresh) throws Exception {
		HctResult result = new HctResult();

		HctBackTestJsonController controller = new HctBackTestJsonController(
				context);

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

		MachineListEntity listEntity = null;
		if (!bTopRefresh) {
			/**
			 * 首先尝试从db中查询
			 */
			List<MachineEntity> machineEntities = selectMachineListFromDb();
			if (machineEntities.size() > 0) {
				listEntity = new MachineListEntity();
				listEntity.dataList = machineEntities;
			}
			/**
			 * 查询不到则从服务器获取
			 */
			else {
				listEntity = getAllMachineFromNetAndInsert2Db(controller,
						params);
			}
		} else if (bTopRefresh) {
			listEntity = getAllMachineFromNetAndInsert2Db(controller, params);
		}

		if (listEntity.dataList != null) {
			result.status = HctConstants.STATUS_SUCCESS;
			if (listEntity.dataList.size() > 0) {

				result.data = listEntity.dataList;
				result.totalSize = listEntity.dataList.size();
			}
		} else {
			result.status = HctConstants.STATUS_FAILD;
		}
		return result;
	}

	/**
	 * 从db查询出"所有机型信息"
	 * 
	 * @return
	 */
	private List<MachineEntity> selectMachineListFromDb() {
		/**
		 * 插入db
		 */
		DbController dbController = new DbController(new DbAdapter(context));
		return dbController.getMachineEntityLst("");
	}

	/**
	 * 将获取到的"所有机型信息"插入db
	 */
	private void insertMachineList2Db(MachineListEntity listEntity) {
		/**
		 * 插入db
		 */
		DbController dbController = new DbController(new DbAdapter(context));
		dbController.insert(listEntity);
	}

	private MachineListEntity getAllMachineFromNetAndInsert2Db(
			HctBackTestJsonController controller,
			ArrayList<NameValuePair> params) throws Exception, JSONException {
		MachineListEntity listEntity;
		String jsonString = !controller.isB_DEBUG() ? mServerAdapter
				.invokeServerGet(HctConstants.NET_SYNC_DATA_MOBILE_PATH,
						GET_ALL_MACHINES_ACTION, params) : controller
				.getAllMachines();

		JSONObject jsonObject = new JSONObject(jsonString);

		listEntity = MachineListEntity.parse(jsonObject);
		if (listEntity.dataList != null) {
			insertMachineList2Db(listEntity);
		}
		return listEntity;
	}

	/**
	 * 4、根据系列ID获取资料(不支持翻页)
	 * 
	 * @param seriesId
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public HctResult getBooksBySeriesId(final String seriesId) throws Exception {
		HctResult result = new HctResult();

		HctBackTestJsonController controller = new HctBackTestJsonController(
				context);

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

		params.add(new BasicNameValuePair("seriesId", seriesId));

		String jsonString = !controller.isB_DEBUG() ? mServerAdapter
				.invokeServerGet(HctConstants.NET_SYNC_DATA_MOBILE_PATH,
						GET_BOOKS_BY_SERIES_ID_ACTION, params) : controller
				.getBooksBySeriesId();

		JSONObject jsonObject = new JSONObject(jsonString);

		BookListEntity listEntity = BookListEntity.parse(jsonObject);
		if (listEntity.dataList != null) {
			result.status = HctConstants.STATUS_SUCCESS;
			if (listEntity.dataList.size() > 0) {
				result.data = listEntity.dataList;
				result.totalSize = listEntity.dataList.size();
			}
		} else {
			result.status = HctConstants.STATUS_FAILD;
		}
		return result;
	}

	/**
	 * 从net获取图书列表，然后将其拼凑进Db查询出的Series及ChildSeries内
	 * 
	 * @param bTopRefresh
	 * @return
	 * @throws Exception
	 */
	public HctResult getAllBooksWithDbAllSeriesAndAllChildSeries(
			boolean bTopRefresh) throws Exception {
		HctResult result = new HctResult();

		HctBackTestJsonController controller = new HctBackTestJsonController(
				context);

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

		BookListEntity listEntity = null;
		if (!bTopRefresh) {
			/**
			 * 首先尝试从db中查询
			 */
			List<BookEntity> bookEntities = selectBookListFromDb().dataList;
			if (bookEntities != null && bookEntities.size() > 0) {
				listEntity = new BookListEntity();
				listEntity.dataList = bookEntities;
			}
			/**
			 * 查询不到则从服务器获取
			 */
			else {
				listEntity = getAllBooksFromNetAndInsert2Db(controller, params);
			}
		} else if (bTopRefresh) {
			listEntity = getAllBooksFromNetAndInsert2Db(controller, params);
		}

		if (listEntity.dataList != null) {
			result.status = HctConstants.STATUS_SUCCESS;
			if (listEntity.dataList.size() > 0) {

				SerieListEntity serieListEntity = new SerieListEntity();
				List<SerieEntity> serieEntities = selectSerieListFromDb();
				if (serieEntities.size() > 0) {

					for (SerieEntity serieEntity : serieEntities) {

						serieEntity.childList = getChildSerieListEntityAndBooksUseSerieId(serieEntity.id);
					}
					serieListEntity.dataList = serieEntities;
				}

				result.data = serieListEntity.dataList;
				result.totalSize = serieListEntity.dataList.size();
			}
		} else {
			result.status = HctConstants.STATUS_FAILD;
		}
		return result;

	}

	private List<ChildSerieEntity> getChildSerieListEntityAndBooksUseSerieId(
			String seriesId) {
		/**
		 * 插入db
		 */
		DbController dbController = new DbController(new DbAdapter(context));
		return dbController.getChildSerieListEntityAndBooksUseSerieId(seriesId);
	}

	public List<ChildSerieEntity> getChildSerieListEntityUseSerieId(
			String seriesId) {
		/**
		 * 插入db
		 */
		DbController dbController = new DbController(new DbAdapter(context));
		return dbController.getChildSerieListEntityUseSerieId(seriesId, 0);
	}

	/**
	 * 从服务器获取All Books，然后insert 到Db
	 * 
	 * @param controller
	 * @param params
	 * @return
	 * @throws Exception
	 * @throws JSONException
	 */
	private BookListEntity getAllBooksFromNetAndInsert2Db(
			HctBackTestJsonController controller,
			ArrayList<NameValuePair> params) throws Exception, JSONException {
		BookListEntity listEntity;
		params.add(new BasicNameValuePair("personId", LoginResultStoreUtil
				.get(context).personId));
		String jsonString = !controller.isB_DEBUG() ? mServerAdapter
				.invokeServerGet(HctConstants.NET_SYNC_DATA_MOBILE_PATH,
						GET_ALL_BOOKS_ACTION, params) : controller
				.getAllBooks();

		JSONObject jsonObject = new JSONObject(jsonString);

		listEntity = BookListEntity.parse(jsonObject);
		if (listEntity != null) {
			insertBookList2Db(listEntity);
		}
		return listEntity;
	}

	/**
	 * 从db查询出"所有books"
	 * 
	 * @return
	 */
	private BookListEntity selectBookListFromDb() {
		/**
		 * 插入db
		 */
		DbController dbController = new DbController(new DbAdapter(context));
		return dbController.getBookListEntityUseSerieId("", 0);
	}

	/**
	 * 将获取到的"所有books"插入db
	 */
	private void insertBookList2Db(BookListEntity listEntity) {
		/**
		 * 插入db
		 */
		DbController dbController = new DbController(new DbAdapter(context));
		dbController.insert(listEntity);
	}

	/**
	 * 4、获取所有资料(不支持翻页)
	 * 
	 * @param seriesId
	 * @return
	 * @throws Exception
	 */
	public HctResult getAllBooks() throws Exception {
		HctResult result = new HctResult();

		HctBackTestJsonController controller = new HctBackTestJsonController(
				context);

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

		String jsonString = !controller.isB_DEBUG() ? mServerAdapter
				.invokeServerGet(HctConstants.NET_SYNC_DATA_MOBILE_PATH,
						GET_ALL_BOOKS_ACTION, params) : controller
				.getAllBooks();

		JSONObject jsonObject = new JSONObject(jsonString);

		BookListEntity listEntity = BookListEntity.parse(jsonObject);
		if (listEntity.dataList != null) {
			result.status = HctConstants.STATUS_SUCCESS;
			if (listEntity.dataList.size() > 0) {
				result.data = listEntity.dataList;
				result.totalSize = listEntity.dataList.size();
			}
		} else {
			result.status = HctConstants.STATUS_FAILD;
		}
		return result;
	}

	/**
	 * 获取基本数据版本号
	 * 
	 * @return
	 * @throws Exception
	 */
	public HctResult getDataVersionCode() throws Exception {
		HctResult result = new HctResult();

		HctBackTestJsonController controller = new HctBackTestJsonController(
				context);
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

		String jsonString = !controller.isB_DEBUG() ? mServerAdapter
				.invokeServerGet(HctConstants.NET_SYNC_DATA_MOBILE_PATH,
						GET_DATA_VERSION_CODE_ACTION, params) : controller
				.getDataVersionCode();
		JSONObject jsonObject = new JSONObject(jsonString);

		DataVersionCodeEntity entity = DataVersionCodeEntity.parse(jsonObject);

		if (entity instanceof DataVersionCodeEntity) {
			result.status = HctConstants.STATUS_SUCCESS;

			result.data = entity;
		} else {
			result.status = HctConstants.STATUS_FAILD;
		}
		return result;
	}

	// ////////////////////////////
	/**
	 * 调试维修栏目信息
	 */
	public HctResult getAllColumns(boolean bTopRefresh) throws Exception {
		HctResult result = new HctResult();

		HctBackTestJsonController controller = new HctBackTestJsonController(
				context);

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

		ColumnListEntity listEntity = null;
		if (!bTopRefresh) {
			/**
			 * 首先尝试从db中查询
			 */
			ArrayList<ColumnEntity> cEntities = selectColumnListFromDb();

			if (cEntities.size() > 0) {
				listEntity = new ColumnListEntity();
				listEntity.dataList = cEntities;
			}

			/**
			 * 查询不到则从服务器获取
			 */
			if (listEntity == null || listEntity.dataList == null
					|| listEntity.dataList.size() == 0) {
				listEntity = getAllColumnsFromNetAndInsert2Db(controller,
						params);
			}
		} else if (bTopRefresh) {
			listEntity = getAllColumnsFromNetAndInsert2Db(controller, params);
		}
		if (listEntity.dataList != null) {
			result.status = HctConstants.STATUS_SUCCESS;
			if (listEntity.dataList.size() > 0) {

				result.data = listEntity.dataList;
				result.totalSize = listEntity.dataList.size();
			}
		} else {
			result.status = HctConstants.STATUS_FAILD;
		}

		return result;
	}

	/**
	 * 从db查询出"调试维修栏目"
	 * 
	 * @return
	 */
	private ArrayList<ColumnEntity> selectColumnListFromDb() {
		/**
		 * 插入db
		 */
		DbColumnController dbController = new DbColumnController(
				new DbColumnAdapter(context));
		return dbController.getColumnEntityLst();
	}

	private ColumnListEntity getAllColumnsFromNetAndInsert2Db(
			HctBackTestJsonController controller,
			ArrayList<NameValuePair> params) throws Exception, JSONException {
		ColumnListEntity listEntity;
		String jsonString = !controller.isB_DEBUG() ? mServerAdapter
				.invokeServerGet(HctConstants.NET_SYNC_DATA_MOBILE_PATH,
						GET_ALL_COLUMNS_ACTION, params) : controller
				.getAllColumns();

		JSONObject jsonObject = new JSONObject(jsonString);

		listEntity = ColumnListEntity.parse(jsonObject, context);

		if (listEntity.dataList != null) {
			insertColumnList2Db(listEntity);
		}
		return listEntity;
	}

	/**
	 * 将获取到的"调试维修栏目"插入db
	 */
	private void insertColumnList2Db(ColumnListEntity listEntity) {
		/**
		 * 插入db
		 */
		DbColumnController dbController = new DbColumnController(
				new DbColumnAdapter(context));
		dbController.insert(listEntity);
	}

	// /////////
	public HctResult getAllBooksWithAllChildSeriesAndDbSerieName(
			boolean bTopRefresh) throws Exception {
		HctResult result = new HctResult();

		HctBackTestJsonController controller = new HctBackTestJsonController(
				context);

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

		BookListEntity listEntity = null;
		if (!bTopRefresh) {

			List<BookEntity> bookEntities = selectBookListFromDb().dataList;
			if (bookEntities != null && bookEntities.size() > 0) {
				listEntity = new BookListEntity();
				listEntity.dataList = bookEntities;
			}

			else {
				listEntity = getAllBooksFromNetAndInsert2Db(controller, params);
			}
		} else if (bTopRefresh) {
			listEntity = getAllBooksFromNetAndInsert2Db(controller, params);
		}

		if (listEntity.dataList != null) {
			DownloadBookLstInitFinishUtil.saveDownloadBookFinished(context, true);
			DownloadBookLstInitFinishUtil.saveUpdateBookServiceFinished(context,false);
			result.status = HctConstants.STATUS_SUCCESS;
			result.data = listEntity;
			result.totalSize = listEntity.dataList.size();
		} else {
			result.status = HctConstants.STATUS_FAILD;
		}
		return result;

	}

}